import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { showToast } from 'vant'
import { login, getUserInfo, type UserInfo, type LoginParams } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const nickname = computed(() => userInfo.value?.nickname || '用户')
  const avatar = computed(() => userInfo.value?.avatar || '')
  const storageQuota = computed(() => userInfo.value?.storageQuota || 0)
  const usedStorage = computed(() => userInfo.value?.usedStorage || 0)
  const availableStorage = computed(() => storageQuota.value - usedStorage.value)
  const usagePercentage = computed(() => {
    if (!storageQuota.value) return 0
    return Math.round((usedStorage.value / storageQuota.value) * 100)
  })

  // 初始化用户信息
  const initUserInfo = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')

    if (savedToken) {
      token.value = savedToken
    }

    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        clearUserInfo()
      }
    }
  }

  // 用户登录
  const userLogin = async (params: LoginParams) => {
    try {
      const response = await login(params)

      token.value = response.token
      userInfo.value = response.user

      // 保存到本地存储
      localStorage.setItem('token', response.token)
      localStorage.setItem('userInfo', JSON.stringify(response.user))

      showToast({
        type: 'success',
        message: '登录成功'
      })

      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    try {
      const info = await getUserInfo()
      userInfo.value = info
      localStorage.setItem('userInfo', JSON.stringify(info))
      return info
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 用户登出
  const userLogout = () => {
    clearUserInfo()
    showToast({
      type: 'success',
      message: '已退出登录'
    })
  }

  // 清除用户信息
  const clearUserInfo = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 更新用户存储使用量
  const updateStorageUsage = (usedSize: number) => {
    if (userInfo.value) {
      userInfo.value.usedStorage = usedSize
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'

    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  return {
    // 状态
    userInfo,
    token,

    // 计算属性
    isLoggedIn,
    nickname,
    avatar,
    storageQuota,
    usedStorage,
    availableStorage,
    usagePercentage,

    // 方法
    initUserInfo,
    userLogin,
    refreshUserInfo,
    userLogout,
    clearUserInfo,
    updateStorageUsage,
    formatFileSize
  }
})